//
//  MBUserDetailController.m
//  LiveBroadcast
//
//  Created by 肖剑 on 2019/2/20.
//  Copyright © 2019 moonBroadcast. All rights reserved.
//

#import "MBUserDetailController.h"
#import "VICMAImageView.h"
#import "MBUserCollectionCell.h"
#import "MBIMController.h"
#import "MBMessageListController.h"
#import "MBShortVideoPlayController.h"
#import <ViewDeck/ViewDeck.h>
@interface MBUserDetailController ()<UIScrollViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,IIViewDeckControllerDelegate,UINavigationControllerDelegate>
{
    MBBaseScrollView *_scrollView;
    UICollectionView *_collectionView;
    UIView *btView;
    MBButton *headPhotoBtn;
    UIImageView *topView;
}
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@property (nonatomic,strong)UIImage *selectImage;
@property(nonatomic, strong)UIView *rightIMButton;
@property (nonatomic, strong)NSDictionary *worksD;
@property (nonatomic, strong)NSDictionary *privateD;
@property (nonatomic, strong)NSDictionary *likeD;
@property (nonatomic, strong)NSMutableArray *dataSource;
@property (nonatomic,assign)NSInteger type;
@property (nonatomic,assign)NSInteger selectType;
@property (nonatomic,copy)NSString *imageUrl;

@end

@implementation MBUserDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.viewDeckController.delegate = self;
    self.navigationController.delegate = self;
     self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.rightIMButton];
    self.worksD = [NSDictionary dictionary];
    self.privateD = [NSDictionary dictionary];
    self.likeD = [NSDictionary dictionary];
    
    _scrollView = [[MBBaseScrollView alloc] initWithFrame:CGRectMake(0, 0, IPHONE_SCREEN_WIDTH, IPHONE_SCREEN_HEIGHT)];
    _scrollView.backgroundColor = [UIColor whiteColor];
    _scrollView.delegate = self;
    self.view = _scrollView;
    if (self.userId == nil) {
        // 初始化控件
        [self initView];
        NSLog(@"self.userId == nil");
    }
}

- (void)setUserId:(NSString *)userId
{
    _userId = userId;
    NSDictionary *dict = @{
                           @"userId":[NSString stringWithFormat:@"%@",[MBUserModel sharedMBUserModel].userInfo.userId],
                           @"beUserId":_userId
                           };
    [MBHttpRequset requestWithUrl:kTradeid_userCenter_getPersonalData setParams:dict isShowProgressView:NO success:^(id  _Nonnull AJson) {
        self.userModel = [[MBUserCenterModel alloc]initWithDict:AJson];
        // 初始化控件
        [self initView];
        NSLog(@"self.userId !!!");
    } failure:^(id  _Nonnull AJson) {
    }];
}

// 初始化控件
- (void)initView
{
    // 用户顶部图
    topView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0,IPHONE_SCREEN_WIDTH,200)];
//    topView.image = [UIImage imageNamed:@"danshuiyu.png"];
    topView.contentMode = UIViewContentModeScaleAspectFill;
    topView.clipsToBounds = YES;
    topView.userInteractionEnabled=YES;
    [topView sd_setImageWithURL:[NSURL URLWithString:self.userModel.userInfo.backgroundUrl] placeholderImage:[UIImage imageNamed:@"danshuiyu.png"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
    }];
    //初始化一个手势
    UITapGestureRecognizer *tapGesturRecognizer=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(topViewClick)];
    //为图片添加手势
    [topView addGestureRecognizer:tapGesturRecognizer];
    [_scrollView addSubview:topView];
    
    // 头像
    // 头像
    headPhotoBtn = [MBButton buttonWithType:UIButtonTypeCustom];
    headPhotoBtn.frame = CGRectMake(20, 170, 90, 90);
    headPhotoBtn.layer.cornerRadius = 45;
    //[MBUserModel sharedMBUserModel].userInfo.headUrl
    NSURL *url = [NSURL URLWithString:self.userModel.userInfo.headUrl];
    [headPhotoBtn sd_setBackgroundImageWithURL:url forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"danshuiyu.png"]];
    headPhotoBtn.clipsToBounds = YES;
    [_scrollView addSubview:headPhotoBtn];
    // 关注
    MBButton *attentionBtn = [MBButton buttonWithType:UIButtonTypeCustom];
    attentionBtn.frame = CGRectMake(30, headPhotoBtn.bottom - 20, 70, 20);
    [attentionBtn setImage:[UIImage imageNamed:@"addguanzhu.png"] forState:UIControlStateNormal];
    [attentionBtn setTitle:@"关注" forState:UIControlStateNormal];
    attentionBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    attentionBtn.backgroundColor = kColorRGBA(255, 128, 0, 1);
    attentionBtn.layer.cornerRadius = 10;
    [_scrollView addSubview:attentionBtn];
    
    if ([[NSString stringWithFormat:@"%@",self.userModel.focuState] isEqualToString:@"1"]) {
        [attentionBtn setTitle:@"已关注" forState:UIControlStateNormal];
        [attentionBtn setImage:nil forState:UIControlStateNormal];
        attentionBtn.backgroundColor = kColorRGBA(102, 102, 102, 1);
    }
    MBButton *rAttentionBtn = attentionBtn;
    attentionBtn.miBtnBlock = ^(){
//        if ([rAttentionBtn.currentTitle isEqualToString:@"已关注"]) {
//
//        }else{
            NSDictionary *dict = @{
                                   @"userId":filter([MBUserModel sharedMBUserModel].userInfo.userId),
                                   @"befansId":filter(self.userModel.userInfo.uId),
                                   @"type":@"3"
                                   };
            [MBHttpRequset requestWithUrl:kTradeid_userCenter_setFocusUs setParams:dict isShowProgressView:NO success:^(id  _Nonnull AJson) {
                if ([rAttentionBtn.currentTitle isEqualToString:@"已关注"]) {
                    [rAttentionBtn setImage:[UIImage imageNamed:@"addguanzhu.png"] forState:UIControlStateNormal];
                    [rAttentionBtn setTitle:@"关注" forState:UIControlStateNormal];
                    rAttentionBtn.backgroundColor = kColorRGBA(255, 128, 0, 1);
                }else{
                    [rAttentionBtn setTitle:@"已关注" forState:UIControlStateNormal];
                    [rAttentionBtn setImage:nil forState:UIControlStateNormal];
                    rAttentionBtn.backgroundColor = kColorRGBA(102, 102, 102, 1);
                }
            } failure:^(id  _Nonnull AJson) {
            }];
//        }
        
    };
    // ID
//    UILabel *idLbl = [[UILabel alloc]init];
//    idLbl.frame = CGRectMake(headPhotoBtn.right + 20, topView.bottom + 10, 30, 20);
//    idLbl.text = @"ID:";
//    idLbl.font = [UIFont boldSystemFontOfSize:16.0];
//    [_scrollView addSubview:idLbl];
    
    UILabel *userIDLbl = [[UILabel alloc]init];
    userIDLbl.frame = CGRectMake(headPhotoBtn.right + 20, topView.bottom + 10, 100, 20);
    userIDLbl.text = [NSString stringWithFormat:@"%@",self.userModel.userInfo.userId];
    userIDLbl.font = [UIFont boldSystemFontOfSize:16.0];
    [_scrollView addSubview:userIDLbl];
    
    // 性别
    UIImageView *sexImgV = [[UIImageView alloc]init];
    sexImgV.frame = CGRectMake(userIDLbl.right, userIDLbl.top + 2, 15, 15);
    NSString *gender;
    if ([self.userModel.userInfo.gender isEqualToString:@"0"])
        gender = @"nv.png";
    else if([self.userModel.userInfo.gender isEqualToString:@"1"])
        gender = @"nan.png";
    else
        gender = @"";
    sexImgV.image = [UIImage imageNamed:@"nv.png"];
    [_scrollView addSubview:sexImgV];
    
    // 粉丝
    UILabel *fansLbl = [[UILabel alloc]init];
    fansLbl.frame = CGRectMake(headPhotoBtn.right + 20, userIDLbl.bottom + 10, 100, 20);
    fansLbl.text = [NSString stringWithFormat:@"粉丝：%@",self.userModel.userInfo.fansTotal];
    fansLbl.textColor = kColorRGBA(102, 102, 102, 102);
    fansLbl.font = [UIFont systemFontOfSize:14.0f];
    [_scrollView addSubview:fansLbl];

    // 关注
    UILabel *attentionLbl = [[UILabel alloc]init];
    attentionLbl.frame = CGRectMake(fansLbl.right , userIDLbl.bottom + 10, 100, 20);
    attentionLbl.text = [NSString stringWithFormat:@"关注：%@",self.userModel.userInfo.focusTotal];
    attentionLbl.textColor = kColorRGBA(102, 102, 102, 102);
    attentionLbl.font = [UIFont systemFontOfSize:14.0f];
    [_scrollView addSubview:attentionLbl];

    // 定位
    UIButton *opsBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    opsBtn.frame = CGRectMake(headPhotoBtn.left, headPhotoBtn.bottom + 20, IPHONE_SCREEN_WIDTH - 40, 20);
    [opsBtn setImage:[UIImage imageNamed:@"dingw.png"] forState:UIControlStateNormal];
    [opsBtn setTitleColor:kColorRGBA(102, 102, 102, 102) forState:UIControlStateNormal];
    [opsBtn setTitle:@"广东省  广州市" forState:UIControlStateNormal];
    [opsBtn.titleLabel setFont:[UIFont systemFontOfSize:12.0f]];
    opsBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -(opsBtn.width /2 + 50) , 0, 0);
    opsBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -(opsBtn.width/2 + 70) , 0, 0);
    [_scrollView addSubview:opsBtn];
    
    // 心情
    UILabel *referralLbl = [[UILabel alloc]init];
    referralLbl.frame = CGRectMake(attentionBtn.left, opsBtn.bottom, IPHONE_SCREEN_WIDTH - (opsBtn.left *2), 40);
    referralLbl.text = (self.userModel.userInfo.referral.length != 0) ? self.userModel.userInfo.referral:@"这人很懒，没写下任何签名";
    referralLbl.textColor = kColorRGBA(102, 102, 102, 102);
    referralLbl.numberOfLines = 0;
    referralLbl.font = [UIFont systemFontOfSize:14.0];
    [_scrollView addSubview:referralLbl];
    
    UIView *referralLine = [[UIView alloc]initWithFrame:CGRectMake(10, referralLbl.bottom, IPHONE_SCREEN_WIDTH - 20, 0.5)];
    referralLine.backgroundColor = [UIColor colorWithRed:238/255.0 green:238/255.0 blue:238/255.0 alpha:1.0];
    [_scrollView addSubview:referralLine];
    
    // 个人标签
    UILabel *userLbl = [[UILabel alloc]init];
    userLbl.frame = CGRectMake(headPhotoBtn.left, referralLine.bottom + 10, IPHONE_SCREEN_WIDTH - 40, 20);
    userLbl.text = @"个人标签";
    userLbl.font = [UIFont systemFontOfSize:16.0];
    [_scrollView addSubview:userLbl];
    
    
    for (int i = 0; i < self.userModel.userInfo.fakeLabel.count; i ++) {
        UILabel *videoLbl = [[UILabel alloc]init];
        videoLbl.frame = CGRectMake(headPhotoBtn.left, userLbl.bottom + 10, (IPHONE_SCREEN_WIDTH - 50)/8, 20);
        videoLbl.textColor = kColorRGBA(102, 102, 102, 102);
        videoLbl.backgroundColor = kColorRGBA(202, 202, 202, 202);
        videoLbl.layer.cornerRadius = 10;
        videoLbl.clipsToBounds = YES;
        videoLbl.textAlignment = NSTextAlignmentCenter;
        videoLbl.font = [UIFont systemFontOfSize:12.0];
        videoLbl.text = self.userModel.userInfo.fakeLabel[i];
        videoLbl.left = headPhotoBtn.left + i*((IPHONE_SCREEN_WIDTH - 45)/8 + 10);
        [_scrollView addSubview:videoLbl];
    }
    
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(0,userLbl.bottom + 30 + 10,IPHONE_SCREEN_WIDTH,20);
    label.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1.0];
    [_scrollView addSubview:label];
    
    // 作品
    UIView *bottomView = [[UIView alloc]init];
    bottomView.frame = CGRectMake(0, label.bottom, IPHONE_SCREEN_WIDTH, IPHONE_SCREEN_HEIGHT - label.bottom - 10 + label.bottom - 64 - 5);
    bottomView.backgroundColor = self.view.backgroundColor;
    _scrollView.contentSize = CGSizeMake(IPHONE_SCREEN_WIDTH, bottomView.bottom);
    [_scrollView addSubview:bottomView];
    btView = bottomView;
    
    NSLog(@"%@",[MBUserModel sharedMBUserModel].userInfo.userId);
    if (self.userModel.userInfo.uId != [MBUserModel sharedMBUserModel].userInfo.userId) {
        MBButton *worksV = [MBButton buttonWithType:UIButtonTypeCustom];
        worksV.frame = CGRectMake(0, 0, IPHONE_SCREEN_WIDTH, 44);
        [worksV setTitleColor:kColorRGBA(255, 128, 0, 1) forState:UIControlStateNormal];
        [worksV setTitle:[NSString stringWithFormat:@"作品（%@）",self.userModel.worksCount] forState:UIControlStateNormal];
        worksV.titleLabel.textAlignment = NSTextAlignmentCenter;
        [bottomView addSubview:worksV];
        [self getVideosWithType:@"1" pageNo:1 userID:self.userModel.userInfo.uId];
    }else{
//        [self getVideosWithType:@"1" pageNo:1 userID:[MBUserModel sharedMBUserModel].userInfo.userId];
        for (int i = 0; i < 3; i ++) {
            MBButton *worksV = [MBButton buttonWithType:UIButtonTypeCustom];
            worksV.tag = i + 1000;
            worksV.frame = CGRectMake(i*(IPHONE_SCREEN_WIDTH/3), 0, IPHONE_SCREEN_WIDTH/3, 44);
            worksV.titleLabel.textAlignment = NSTextAlignmentCenter;
            if (i == 0) [worksV setTitleColor:kColorRGBA(255, 128, 0, 1) forState:UIControlStateNormal];
            else [worksV setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [worksV addTarget:self action:@selector(worksClick:) forControlEvents:UIControlEventTouchUpInside];
            [bottomView addSubview:worksV];
        }
    }
    
    UIView *worksVLine = [[UIView alloc]initWithFrame:CGRectMake(10, 44, IPHONE_SCREEN_WIDTH - 20, 0.5)];
    worksVLine.backgroundColor = [UIColor colorWithRed:238/255.0 green:238/255.0 blue:238/255.0 alpha:1.0];
    [bottomView addSubview:worksVLine];
    
    // 作品
    UICollectionViewFlowLayout *fl = [[UICollectionViewFlowLayout alloc]init];
    UICollectionView *colletionV = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 45, IPHONE_SCREEN_WIDTH, bottomView.height - 45) collectionViewLayout:fl];
    colletionV.delegate = self;
    colletionV.dataSource = self;
    colletionV.backgroundColor = _scrollView.backgroundColor;
    [bottomView addSubview: colletionV];
    colletionV.scrollEnabled = NO;
    _collectionView = colletionV;
    //布局
    fl.minimumInteritemSpacing = 0;
    fl.minimumLineSpacing = 5;
    [_collectionView registerNib:[UINib nibWithNibName:@"MBUserCollectionCell" bundle:nil] forCellWithReuseIdentifier:@"USERCONLECTIONCELL"];
    
//
//
    [self getVideosWithType:@"1" pageNo:1 userID:@"1"];
    
    MB_WeakSelf(self);
    headPhotoBtn.miBtnBlock = ^(){
        [weakself openCamera];
        weakself.selectType = 0;
    };
}

- (void)topViewClick
{
    // 判断是否是自己
    
    NSLog(@"头部点击事件");
    
    [self openCamera];
    self.selectType = 1;
}

- (void)uploadImg:(NSString *)no
{
    NSDictionary *dict = @{
                           @"pictureUrl":self.imageUrl,
                           @"type":no,
                           @"userId":[NSString stringWithFormat:@"%@",[MBUserModel sharedMBUserModel].userInfo.userId]
                           };
    
    [MBHttpRequset requestWithUrl:kTradeid_userCenter_setHeadOrBackGroundUrl setParams:dict isShowProgressView:YES success:^(id  _Nonnull AJson) {
        NSLog(@"kTradeid_userCenter_setHeadOrBackGroundUrl  == %@",AJson);
        
        [MBUserModel sharedMBUserModel].userInfo.headUrl = AJson[@"pictureUrl"];
        [[MBUserModel sharedMBUserModel].userInfo setHeadUrl:AJson[@"pictureUrl"]];
        [self archiveDatas:[MBUserModel sharedMBUserModel]];
         NSLog(@"更换后 = %@",[MBUserModel sharedMBUserModel].userInfo.headUrl);
    } failure:^(id  _Nonnull AJson) {
        
    }];
}

// 打开相机
- (void)openCamera{
    MB_WeakSelf(self);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *photographAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself takePhoto];
    }];
    UIAlertAction *selectPictureAction = [UIAlertAction actionWithTitle:@"从图库中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself pushTZImagePickerController];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:photographAction];
    [alert addAction:selectPictureAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}

/*拍照*/
-(void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        // 无相机权限 做一个友好的提示
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self takePhoto];
                });
            }
        }];
        // 拍照之前还需要检查相册权限
    } else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
    } else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            self.imagePickerVc.sourceType = sourceType;
            NSMutableArray *mediaTypes = [NSMutableArray array];
            [mediaTypes addObject:(NSString *)kUTTypeImage];
            if (mediaTypes.count) {
                _imagePickerVc.mediaTypes = mediaTypes;
            }
            [self presentViewController:_imagePickerVc animated:YES completion:nil];
        } else {
            NSLog(@"模拟器中无法打开照相机,请在真机中使用");
        }
    }
}

-(void)pushTZImagePickerController{
    MB_WeakSelf(self);
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    imagePickerVc.isSelectOriginalPhoto = YES;
    imagePickerVc.allowTakeVideo = NO;
    imagePickerVc.allowTakePicture = NO;
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowCrop = NO;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        UIImage *image = photos.firstObject;
        NSData *data = UIImageJPEGRepresentation(image, 0.5);
        UIImage *resultImage = [UIImage imageWithData:data];
        weakself.selectImage = resultImage;
        if (weakself.selectType == 0) {// 头像
            [self->headPhotoBtn setImage:resultImage forState:UIControlStateNormal];
        }else{// 背景图
            self->topView.image = resultImage;
        }
        [self getQiniuUpToken:resultImage];
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    MB_WeakSelf(self);
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSData *data = UIImageJPEGRepresentation(image, 0.5);
    UIImage *resultImage = [UIImage imageWithData:data];
    self.selectImage = resultImage;
    if (weakself.selectType == 0) {// 头像
        [self->headPhotoBtn setImage:resultImage forState:UIControlStateNormal];
    }else{// 背景图
        self->topView.image = resultImage;
    }
    [self getQiniuUpToken:resultImage];
}

#pragma mark - getter and setter
- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (@available(iOS 9, *)) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
        
    }
    return _imagePickerVc;
}

/**
 获取七牛Token
 */
-(void)getQiniuUpToken:(UIImage *)img{
    NSDictionary *param = @{
                            };
    [MBHttpRequset requestWithUrl:kThird_Qiniu_Token setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        NSLog(@"kThird_Qiniu_Token = %@",AJson);
        QNUploadManager *manager = [[QNUploadManager alloc]init];
        NSData *data = UIImageJPEGRepresentation(img, 0.7);
        NSString *timeKey = [NSString stringWithFormat:@"%zd",[[MBTimeManager shateInstance]getCurrentTimestamp]];
        NSString *imageName = [NSString stringWithFormat:@"%@%@%@%@%@",@"upload/image/userId=",[MBUserModel sharedMBUserModel].userInfo.userId,@"-",timeKey,@".jpg"];
        
        [manager putData:data key:imageName token:AJson[@"upToken"] complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
            if (info.statusCode == 200) {
                
                self.imageUrl = [NSString stringWithFormat:@"%@",resp[@"key"]];
                if (self.selectType == 0) {// 头像
                    [self uploadImg:@"1"];
                }else{// 背景图
                    [self uploadImg:@"2"];
                }
            }
        } option:nil];
    } failure:^(id  _Nonnull AJson) {
        
    }];
}


- (void)worksClick:(MBButton *)btn
{
    NSInteger type = btn.tag - 1000 + 1;
//    [self getVideosWithType:[NSString stringWithFormat:@"%ld",(long)type] pageNo:1 userID:[MBUserModel sharedMBUserModel].userInfo.userId];
    [self getVideosWithType:[NSString stringWithFormat:@"%ld",(long)type] pageNo:1 userID:@"1"];
    MBButton *btn1 = (MBButton *)[btView viewWithTag:1000];// 作品
    MBButton *btn2 = (MBButton *)[btView viewWithTag:1001];// 私密
    MBButton *btn3 = (MBButton *)[btView viewWithTag:1002];// 喜欢
    switch (btn.tag) {
        case 1000:
        {
            self.type = 1000;
            [btn1 setTitleColor:kColorRGBA(255, 128, 0, 1) forState:UIControlStateNormal];
            [btn2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [btn3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            
            [self getVideosWithType:@"1" pageNo:1 userID:self.userModel.userInfo.uId];
//            NSArray *arr = self.worksD[@"worksList"];
//            [self setCollectionHWithArr:arr];
        }
            break;
        case 1001:
        {
            self.type = 1001;
            [btn2 setTitleColor:kColorRGBA(255, 128, 0, 1) forState:UIControlStateNormal];
            [btn1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [btn3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            
            [self getVideosWithType:@"2" pageNo:1 userID:self.userModel.userInfo.uId];
//            NSArray *arr = self.worksD[@"privacysList"];
//            [self setCollectionHWithArr:arr];
        }
            break;
        case 1002:
        {
            self.type = 1002;
            [btn3 setTitleColor:kColorRGBA(255, 128, 0, 1) forState:UIControlStateNormal];
            [btn2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [btn1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            
            [self getVideosWithType:@"3" pageNo:1 userID:self.userModel.userInfo.uId];
//            NSArray *arr = self.worksD[@"likesList"];
//            [self setCollectionHWithArr:arr];
        }
            break;
        default:
            break;
    }
}

- (void)setCollectionHWithArr:(NSArray *)arr
{
    NSLog(@"setCollectionHWithArr = %@",arr);
    if (arr.count != 0) {
        _collectionView.height = ((IPHONE_SCREEN_WIDTH - 20)/3) * (arr.count/3 + arr.count%3) + ((arr.count/3) + arr.count%3 - 1)* 20;
    }
    _scrollView.contentSize = CGSizeMake(0, btView.top + _collectionView.height + 44);
    [_collectionView reloadData];
}

- (void)setBottomVTitleWithDict:(NSDictionary *)dict
{
    MBButton *btn = (MBButton *)[btView viewWithTag:1000];
    [btn setTitle:[NSString stringWithFormat:@"作品（%@）",dict[@"worksCount"]] forState:UIControlStateNormal];
    
    MBButton *btn1 = (MBButton *)[btView viewWithTag:1001];
    [btn1 setTitle:[NSString stringWithFormat:@"私密（%@）",dict[@"privacyCount"]] forState:UIControlStateNormal];
    
    MBButton *btn2 = (MBButton *)[btView viewWithTag:1002];
    [btn2 setTitle:[NSString stringWithFormat:@"喜欢（%@）",dict[@"likeCount"]] forState:UIControlStateNormal];
}

- (UIView *)rightIMButton
{
    if (_rightIMButton == nil) {
        UIView *view = [[UIView alloc] init];
        view.frame = CGRectMake(0, 0, 60, 30);
        
        MBButton *imBtn = [MBButton buttonWithType:UIButtonTypeCustom];
        imBtn.frame = CGRectMake(0, 0, 30, 30);
        [imBtn setImage:[UIImage imageNamed:@"sixin1.png"] forState:UIControlStateNormal];
        [view addSubview:imBtn];
        
        MBButton *shareBtn = [MBButton buttonWithType:UIButtonTypeCustom];
        shareBtn.frame = CGRectMake(30, 0, 30, 30);
        [shareBtn setImage:[UIImage imageNamed:@"un-fenxiang.png"] forState:UIControlStateNormal];
        [view addSubview:shareBtn];
        
        imBtn.miBtnBlock = ^(){
            
            if (self.userModel.userInfo.uId != [MBUserModel sharedMBUserModel].userInfo.userId) {
                MBIMController *rcConverstionVC = [[MBIMController alloc]initWithConversationType:RC_CONVERSATION_MODEL_TYPE_NORMAL targetId:[NSString stringWithFormat:@"%@",self.userModel.userInfo.uId]];
                rcConverstionVC.title = self.userModel.userInfo.nickname;
                rcConverstionVC.userModel = self.userModel;
                [self.navigationController pushViewController:rcConverstionVC animated:YES];
            }else{
                // 私信列表
                MBMessageListController *listVC = [[MBMessageListController alloc]init];
                listVC.title = @"私信";
                [self.navigationController pushViewController:listVC animated:YES];
            }
            
            
            
        };
        
        _rightIMButton = view;
    }
    return _rightIMButton;
}


- (void)setUserModel:(MBUserCenterModel *)userModel
{
    _userModel = userModel;
    NSLog(@"userModel ============== %@",userModel.userInfo.uId);
}

// 获取作品/私密/喜欢
- (void)getVideosWithType:(NSString *)type pageNo:(NSInteger)pageNo userID:(NSString *)uid
{
    NSDictionary *dict = @{
                           @"userId":filter(uid),
                           @"type":type,
                           @"pageNo":[NSString stringWithFormat:@"%ld",(long)pageNo]
                           };
//    UICollectionView *reCollectionView = _collectionView;
    [MBHttpRequset requestWithUrl:kTradeid_userCenter_getPersonalClassify setParams:dict isShowProgressView:NO success:^(id  _Nonnull AJson) {
        [self setBottomVTitleWithDict:AJson];
        NSLog(@"kTradeid_userCenter_getPersonalClassify = %@",AJson);
        if ([type isEqualToString:@"1"])
        {
            self.worksD = AJson;
            NSArray *arr = self.worksD[@"worksList"];
            [self setCollectionHWithArr:arr];
        }else if([type isEqualToString:@"2"]){
            self.privateD = AJson;
            NSArray *arr = self.worksD[@"privacysList"];
            [self setCollectionHWithArr:arr];
        }else{
            self.likeD = AJson;
            NSArray *arr = self.worksD[@"likesList"];
            [self setCollectionHWithArr:arr];
        }
//        [reCollectionView reloadData];
    } failure:^(id  _Nonnull AJson) {
        
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    
    //设置导航栏透明
    [self.navigationController.navigationBar setTranslucent:true];
    //把背景设为空
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    //处理导航栏有条线的问题
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setTranslucent:NO];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//    NSLog(@"  x %f   y  %f ",scrollView.contentOffset.x,scrollView.contentOffset.y);
    if (scrollView.contentOffset.y  >= 200) {
        self.title = self.userModel.userInfo.nickname;
//        _collectionView.scrollEnabled = YES;
        [UIView animateWithDuration:0.5f animations:^{
            [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
            [self.navigationController.navigationBar setShadowImage:nil];
        }];
    }else{
        self.title = @"";
//        _collectionView.scrollEnabled = NO;
        [UIView animateWithDuration:0.5f animations:^{
            //设置导航栏透明
            [self.navigationController.navigationBar setTranslucent:true];
            //把背景设为空
            [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
            //处理导航栏有条线的问题
            [self.navigationController.navigationBar setShadowImage:[UIImage new]];
        }];
    }
}


#pragma mark - UICollectionView delegate & dataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
    
}



- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.userModel.userInfo.uId != [MBUserModel sharedMBUserModel].userInfo.userId) {
        self.dataSource = self.worksD[@"worksList"];
        NSLog(@" worksList   dataSource = %@",self.dataSource);
        return self.dataSource.count;
    }else{
        if (self.type == 1001) {
            self.dataSource = self.privateD[@"privacysList"];
        }else if(self.type == 1002){
            self.dataSource = self.likeD[@"likesList"];
        }else{
            self.dataSource = self.worksD[@"worksList"];
        }
        NSLog(@"dataSource = %@",self.dataSource);
        return self.dataSource.count;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((IPHONE_SCREEN_WIDTH - 20)/3, (IPHONE_SCREEN_WIDTH - 20)/3);
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 5, 5, 5);
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MBUserCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"USERCONLECTIONCELL" forIndexPath:indexPath];
//    NSArray *arr = self.worksD[@"worksList"];
    if (self.dataSource.count != 0){
        NSDictionary *dict = self.dataSource[indexPath.row];
        [cell.videoImg sd_setImageWithURL:dict[@"coverUrl"] placeholderImage:[UIImage imageNamed:@"danshuiyu.png"]];
        if ([dict[@"type"] isEqualToString:@"1"]) {//短视频
            cell.flagImg.image = [UIImage imageNamed:@"duanship.png"];
        }else{//图片
            cell.flagImg.image = [UIImage imageNamed:@"pic.png"];
        }
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"self.dataSource  = %@",self.dataSource);
    NSDictionary *dict = self.dataSource[indexPath.row];
    if ([dict[@"type"] isEqualToString:@"1"]) {
        MBShortVideoPlayController *vc = [[MBShortVideoPlayController alloc]init];
        vc.videoPath = dict[@"videoUrl"];
        vc.videoID = dict[@"id"];
        vc.videoType = dict[@"type2"];
        vc.entityType = @"1";
        [self.navigationController pushViewController:vc animated:YES];
        
    }else {
        MBShortVideoPlayController *vc = [[MBShortVideoPlayController alloc]init];
        vc.videoPath = dict[@"videoUrl"];
        vc.videoID = dict[@"id"];
        vc.videoType = dict[@"type2"];
        vc.entityType = @"2";
        [self.navigationController pushViewController:vc animated:YES];
    }
}




- (BOOL)viewDeckController:(IIViewDeckController *)viewDeckController willOpenSide:(IIViewDeckSide)side
{
    //IIViewDeckSideRight
    if (side == IIViewDeckSideRight) {
        return NO;
    }
    [self.navigationController popViewControllerAnimated:YES];
    return NO;
}

//- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
//{
//    
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
